from emmodels.em_base_data import BaseData
from emmodels.em_his_series import DetailHisSeries
from emutils.time_utils import get_offset_day
import tushare as ts
import datetime
from emmongo import em_mongomanager as mongoManager
# 首先查询股票基本信息表，维持一个字典{'id':'stkcode'},同时存放一个list
# 然后依次pop 这个list里面的item, 对每个item 从 tushare上 查询
# 最后插入,不需要从code映射回去，直接就拿stkcode作为key


base_datas = BaseData.select_all()
m = 0
print('开始插入')


def sys_all():

    for i in range(len(base_datas)):
        item = base_datas[i]
        begin_time = datetime.datetime.now()
        print('插入第%d条数据，共需要插入%d条数据' % (i, len(base_datas)))

        stkCode = item.stkcode
        ipodate = item.ipodate
        stkname = item.stkname

        if ipodate == None:
            print("新股未上市")
            continue
        if stkCode == None:
            continue
        last_his = DetailHisSeries.select_last(stkCode)
        start_date = None
        if last_his and last_his.datatime:
            start_date = min(last_his.datatime, datetime.datetime.now())
        else:
            start_date = ipodate

        end_date = datetime.datetime.now()

        l = sys_stk_his(start_date, end_date, stkCode, ipodate)

        # if len(l) >0:
            # HisSeries.insert_list(l,append_dup_list=['stockid', 'datatime', 'period'])
            # print('插入%s(%s)所有从%s到%s这段时间周期数据,耗时%d秒' % (stkname, stkCode, start_date.strftime('%Y-%m-%d'), end_date.strftime('%Y-%m-%d'),
            #                                           (datetime.datetime.now() - begin_time).seconds))
        # else:
        #     print("无数据同步")
        # l.clear()
    print('插入完成')

def sys_stk_from_ipodate(stk_code,fetchall=False):
    base_data = BaseData.select_stkcode(stkcode=stk_code)
    if base_data:
        stkCode = base_data.stkcode
        ipodate = base_data.ipodate
        stkname = base_data.stkname
        sys_stk_his(stk_code, ipodate)

    pass

def sys_stk_his(stkCode=None,start_date=None, end_date=datetime.datetime.now(),is_index=False, l_kType=['D'], l_autype=['qfq']):
    l = []
    start = start_date.strftime('%Y-%m-%d')
    end = end_date.strftime('%Y-%m-%d')
    for kType in l_kType:
        for autype in l_autype:
            # end = '2016-11-01 16:00'
            m1 = ts.get_h_data(code=stkCode, start=start, end=end, index=is_index, pause=0.1, autype=kType)


            # m_his_series = [
            #     DetailHisSeries(stockid=stkCode, datatime=his[0], open=his[1], close=his[2], high=his[3], low=his[4],
            #                     volume=his[5],
            #                     period=kType) for his in m1.values]
            # l.extend(m_his_series)
    return l


# sys_all()

sys_stk_his('000001', start_date=datetime,is_index=True)

